package com.example.mygame.service;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import com.example.mygame.controller.AddFriend;
import com.example.mygame.pojo.Friend;
import com.example.mygame.pojo.Grade;
import com.example.mygame.pojo.User;

import java.util.ArrayList;
import java.util.List;

public class SqliteUtils extends SQLiteOpenHelper {

    // 数据库名称
    private static final String DB_NAME = "game.db";

    // 表名
    private static final String TABLE_NAME_STUDENT = "user";
    private static final String TABLE_NAME_GRADE = "grade";
    private static final String TABLE_NAME_FRIEND = "friend";

    // 字段创建
    private static final String CREATE_TABLE_SQL_STUDENT = "create table " + TABLE_NAME_STUDENT
            + " (id integer primary key autoincrement, user_name text, password text, age text, sex text, phone text, nick text)";

    private static final String CREATE_TABLE_SQL_GRADE = "create table " + TABLE_NAME_GRADE
            + " (id integer primary key autoincrement, user_id integer, score text)";

    private static final String CREATE_TABLE_SQL_FRIEND = "create table " + TABLE_NAME_FRIEND
            + " (id integer primary key autoincrement, username text, friendname text , status integer , nick text ,phone text,UNIQUE (username,friendname) ON CONFLICT REPLACE)";


    public SqliteUtils(Context context) {
        super(context, DB_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_SQL_STUDENT);
        db.execSQL(CREATE_TABLE_SQL_GRADE);
        db.execSQL(CREATE_TABLE_SQL_FRIEND);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    // 注册用户
    public long insertData(User user) {

        SQLiteDatabase db = getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put("user_name", user.getName());
        contentValues.put("password", user.getPassword());
        contentValues.put("age", user.getAge());
        contentValues.put("nick", user.getNick());
        contentValues.put("phone", user.getPhone());
        contentValues.put("sex", user.getSex());
        return db.insert(TABLE_NAME_STUDENT, null, contentValues);
    }

    // 添加成绩
    public long insertData(Grade grade) {

        SQLiteDatabase db = getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put("user_id", grade.getUser_id());
        contentValues.put("score", grade.getGrade());
        return db.insert(TABLE_NAME_GRADE, null, contentValues);
    }

    // 注销账号
    public int deleteDataFromDbByName(String userName) {

        SQLiteDatabase db = getWritableDatabase();
        return db.delete(TABLE_NAME_STUDENT, "user_name = ?", new String[]{userName});
    }

    // 更新用户（修改密码）
    public int updateData(User user) {


        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("nick", user.getNick());
        values.put("age", user.getAge());
        values.put("sex", user.getSex());
        values.put("phone", user.getPhone());
        values.put("password", user.getPassword());

        return db.update(TABLE_NAME_STUDENT, values, "user_name = ?", new String[]{user.getName()});
    }


    // 查询所有用户
    public List<User> queryAllFromDb() {

        SQLiteDatabase db = getReadableDatabase();

        List<User> userList = new ArrayList<>();

        Cursor cursor = db.query(TABLE_NAME_STUDENT, null, null,
                null, null, null, null);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                @SuppressLint("Range")
                String user_name = cursor.getString(cursor.getColumnIndex("user_name"));
                @SuppressLint("Range")
                String password = cursor.getString(cursor.getColumnIndex("password"));
                @SuppressLint("Range")
                String age = cursor.getString(cursor.getColumnIndex("age"));
                @SuppressLint("Range")
                String sex = cursor.getString(cursor.getColumnIndex("sex"));
                @SuppressLint("Range")
                String nick = cursor.getString(cursor.getColumnIndex("nick"));
                @SuppressLint("Range")
                String phone = cursor.getString(cursor.getColumnIndex("phone"));


                User user = new User();
                user.setName(user_name);
                user.setPassword(password);
                user.setPhone(phone);
                user.setNick(nick);
                user.setAge(age);
                user.setSex(sex);

                userList.add(user);
            }
            cursor.close();
        }
        System.out.println(userList);
        return userList;
    }

    public List<User> queryFromDbByName(String userName) {

        SQLiteDatabase db = getReadableDatabase();

        List<User> userList = new ArrayList<>();

        Cursor cursor = db.query(TABLE_NAME_STUDENT, null, "user_name like ?",
                new String[]{userName}, null, null, null);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                @SuppressLint("Range")
                String user_name = cursor.getString(cursor.getColumnIndex("user_name"));
                @SuppressLint("Range")
                String password = cursor.getString(cursor.getColumnIndex("password"));
                @SuppressLint("Range")
                String age = cursor.getString(cursor.getColumnIndex("age"));
                @SuppressLint("Range")
                String sex = cursor.getString(cursor.getColumnIndex("sex"));
                @SuppressLint("Range")
                String nick = cursor.getString(cursor.getColumnIndex("nick"));
                @SuppressLint("Range")
                String phone = cursor.getString(cursor.getColumnIndex("phone"));

                User user = new User();
                user.setName(user_name);
                user.setPassword(password);
                user.setPhone(phone);
                user.setNick(nick);
                user.setAge(age);
                user.setSex(sex);

                userList.add(user);
            }
            cursor.close();
        }

        return userList;
    }

    // 添加朋友
    public long addFriend(Friend friend) {

        SQLiteDatabase db = getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put("username", friend.getUsername());
        contentValues.put("friendname", friend.getFriendname());
        contentValues.put("nick", friend.getNick());
        contentValues.put("phone", friend.getPhone());
        contentValues.put("status", friend.getStatus());
        return db.insertOrThrow(TABLE_NAME_FRIEND, null, contentValues);

//        return db.insert(TABLE_NAME_FRIEND, null, contentValues);


    }

    // 同意对方添加朋友
    public void updateStatus(String username, String friendname, String nick, String phone) {

        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("status", 1);
        List<Friend> friendList = showApply(friendname);
        for (Friend friend : friendList) {
            String friendname1 = friend.getFriendname();
            System.out.println("====");
            System.out.println(friendname1);
            System.out.println("***");
            String username1 = friend.getUsername();
            System.out.println(username1);
            if (friendname1.equals(friendname) && username1.equals(username)) {
                System.out.println("success");
                db.update(TABLE_NAME_FRIEND, values, "username =?", new String[]{username});
                ContentValues contentValues = new ContentValues();
                contentValues.put("username", friendname);
                contentValues.put("friendname", username);
                contentValues.put("nick", nick);
                contentValues.put("phone", phone);
                contentValues.put("status", 1);
                db.insert(TABLE_NAME_FRIEND, null, contentValues);
            }
        }


    }

    // 查看谁申请添加用户为好友
    public List<Friend> showApply(String userName) {

        SQLiteDatabase db = getReadableDatabase();

        Cursor cursor = db.query(TABLE_NAME_FRIEND, null, "friendname = ?",
                new String[]{userName}, null, null, null);

        List<Friend> friendList = new ArrayList<>();

        if (cursor != null) {
            while (cursor.moveToNext()) {
                @SuppressLint("Range")
                String friendname = cursor.getString(cursor.getColumnIndex("friendname"));
                @SuppressLint("Range")
                String status = cursor.getString(cursor.getColumnIndex("status"));
                @SuppressLint("Range")
                String username = cursor.getString(cursor.getColumnIndex("username"));
                @SuppressLint("Range")
                String nick = cursor.getString(cursor.getColumnIndex("nick"));
                @SuppressLint("Range")
                String phone = cursor.getString(cursor.getColumnIndex("phone"));
                if (status.equals("0")) {
                    Friend friend = new Friend();
                    friend.setFriendname(friendname);
                    friend.setStatus(1);
                    friend.setUsername(username);
                    friend.setNick(nick);
                    friend.setPhone(phone);
                    friendList.add(friend);
                }
            }
            cursor.close();
        }

        return friendList;
    }

    // 查看好友
    public List<Friend> showFriend(String userName, String status) {

        SQLiteDatabase db = getReadableDatabase();
        List<Friend> friendList = new ArrayList<>();
        Cursor cursor = db.query(TABLE_NAME_FRIEND, null, "username = ?",
                new String[]{userName}, null, null, null);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                @SuppressLint("Range")
                String friendname = cursor.getString(cursor.getColumnIndex("friendname"));
                @SuppressLint("Range")
                String status1 = cursor.getString(cursor.getColumnIndex("status"));
                @SuppressLint("Range")
                String nick = cursor.getString(cursor.getColumnIndex("nick"));
                @SuppressLint("Range")
                String phone = cursor.getString(cursor.getColumnIndex("phone"));
                if (status1.equals(status)) {
                    Friend friend = new Friend();
                    friend.setFriendname(friendname);
                    friend.setUsername(userName);
                    friend.setNick(nick);
                    friend.setPhone(phone);
                    friendList.add(friend);
                    System.out.println("==========");
                    System.out.println(friend.getFriendname());
                }
            }
            cursor.close();
        }
        return friendList;
    }
}
